<template>
  <div id="testIfram">
    <span class="pdf-scan" v-if="contratInfo.scanPdf" @click="showScan">查看合同扫描件原件</span>
    <div class="pdf-model">
      <a-alert :style="{background: '#fff', border: '0'}" show-icon>
        <template #message><span :style="{color: '#6B7A8B'}">请先滚动合同再选择内容，再选择标签</span></template>
        <template #icon><ExclamationCircleFilled :style="{color: '#CAD3DE'}" /></template>
      </a-alert>
      <a-button @click="showModal" class="search-btn2" :style="{marginRight: '20px',marginLeft: '40px'}">添加标签</a-button>
      <a-button class="search-btn2" shape="circle" @click="showDownModel">
        <template #icon>
          <DownloadOutlined />
        </template>
      </a-button>
    </div>
    <a-modal v-model:visible="visible" title="保存标签" @ok="handleOk" @cancel="closeLabelModel">
      <a-form :model="formState" labelAlign="left">
        <div class="form-item-border">
          <a-form-item label="标签" name="labelValue">
            <a-select :bordered="false"
                      v-model:value="selectTxt"
                      show-search
                      :show-arrow="false"
                      :filter-option="filterOption"
                      :not-found-content="null"
                      :field-names="{ label: 'labelValue', value: 'id'}"
                      :options="searchContractAll"
                      @search="handleSearch"
                      @blur="handleBlur"
                      @change="handleChange"
                      @select="handleSelect"
                      placeholder="请输入标签"
            >
              <template #option="{labelValue, isSyc}">
                <div :style="{width: '100%', display: 'flex', justifyContent: 'space-between'}">
                  <span>{{labelValue}}</span>
                  <span :style="{color: '#F5001D'}" v-if="isSyc">系统</span>
                  <span :style="{color: '#0062AD'}" v-if="!isSyc">个人</span>
                </div>
              </template>
            </a-select>
          </a-form-item>
        </div>
        <div class="form-item-border" :style="{height: '100%'}">
          <a-form-item label="内容" name="labelDetail">
            <a-textarea disabled  :autoSize="{minRows: 4, maxRows: 10}" :bordered="false" :rows="4" v-model:value="formState.labelDetail" placeholder="请输入内容" />
          </a-form-item>
        </div>
      </a-form>
      <template #footer>
        <div class="from-btn-right">
          <a-button key="back" class="border-btn" @click="closeLabelModel">取消</a-button>
          <a-button key="submit" @click="handleOk" class="search-btn1">保存</a-button>
        </div>
      </template>
    </a-modal>
    <a-modal v-model:visible="downVisible" title="下载合同" @ok="downHandleOk" @cancel="closeDownModel">
      <a-alert type="success" show-icon :style="{marginBottom: '24PX'}" v-if="dowMsg">
        <template #message>
          <span>导出成功，请到 <span class="downa" @click="goDown">导出任务</span>中下载</span>
        </template>
      </a-alert>
      <a-form :model="downForm" labelAlign="left">
        <div class="form-item-border">
          <a-form-item label="起始页码" name="startPage">
            <a-input-number :bordered="false" :style="{width: '100%'}" v-model:value="downForm.startPage" placeholder="请输入起始页码" />
          </a-form-item>
        </div>
        <div class="form-item-border">
          <a-form-item label="结束页码" name="endPage">
            <a-input-number :bordered="false" :style="{width: '100%'}" v-model:value="downForm.endPage" placeholder="请输入结束页码" />
          </a-form-item>
        </div>
      </a-form>
      <template #footer>
        <div class="from-btn-right">
          <a-button key="back" class="border-btn" @click="closeDownModel">取消</a-button>
          <a-button key="submit" @click="downHandleOk" class="search-btn1">下载</a-button>
        </div>
      </template>
    </a-modal>
    <div class="red-border" ref="scanf"></div>
    <iframe  name="parentIframe" id="parentIframe" src='/testIndex.html'
             :height="isIframe?'620px' : 0"
             width="100%"/>
    <a-modal v-model:visible="scanVisible" title="合同扫描件原件" :width="600">
      <iframe  name="parentIframeModel" id="parentIframeModel" src='/testIndex.html'
               :height="isIframe?'620px' : 0"
               width="100%"/>
    </a-modal>
    <EmptyDefault v-if="!isIframe"  :descriptionInfo="'合同原件还未上传'"/>

  </div>
</template>

<script setup>
import {ref, onMounted, getCurrentInstance, defineProps, watch, defineEmits} from 'vue'
import { DownloadOutlined, ExclamationCircleFilled } from '@ant-design/icons-vue';
import EmptyDefault from '@/components/EmptyDefault/EmptyDefault.vue'
const { proxy  } = getCurrentInstance()
import $ from "jquery";
import {message} from "ant-design-vue";
import {useRouter} from "vue-router";
const isIframe = ref(false)
const downVisible = ref(false)
const scanVisible = ref(false)
const emit = defineEmits(['saveLabel'])
const props = defineProps({
  originalContract: {
    type: Object,
    required: true,
    default: () => {
      return {
        url: ''
      }
    }
  },
  contractLabels: {
    type: Array,
    required: true,
    default: () => {
      return []
    }

  },
  searchInfo: {
    type: Object,
    default: () => {}
  },
  posionInfo: {
    type:Object,
    default: () => {
      return {}
    }
  }
})
const visible = ref(false)
const isSaveLabel = ref(false)
const selectTxt = ref('')
const formState = ref({
  conId: '',
  labelValue: '',
  labelDetail: '',
  top: '',
  cache: '',
  labelId: '',
  scanPdfX: '',
  scanPdfY: '',
  screenWidth: '',
  screenHeight: '',
})
const downForm = ref({
  id:'',
  startPage: '',
  endPage: ''
})
const areas = ref([]) //系统标签
const contractLabelAll = ref([]) //所有的标签
const searchContractAll = ref([]) //搜索查询出来的标签
const searchTxt = ref({})
// let selectText = ref()
const contratInfo = ref({url: '',conId: '', id: '', contractName: '', scanPdf: '', newUrl: ''})
const posionInfoChild = ref({
  top: '',
  cache: '',
  scanPdfX: '',
  scanPdfY: '',
  screenWidth: '',
  screenHeight: '',
  labelDetail: ''
})
watch(() => props.originalContract, (newVal) => {
  console.log('数据更新了urla', newVal)
  contratInfo.value = newVal
  if (newVal.url) {
    isIframe.value = true
  } else {
    isIframe.value = false
  }
  getMsg()
})
watch(() => props.searchInfo, (newVal) => {
  console.log('搜索的值更新了没', newVal)
  searchTxt.value = newVal
  postSearchMsg()
})
watch(() => props.posionInfo, (newVal) => {
  console.log('定位的值', newVal)
  posionInfoChild.value = newVal
  getPostion()
})
watch(() => props.contractLabels, (newVal) => {
  console.log('数据更新了标签信息', newVal)
  scanf.value.style.display = 'none'
  newVal.map(item => {
    Object.assign(item, {
      isSyc: !!item.labelId,
      id: item.id.toString(),
      labelId:item.labelId? item.labelId.toString() : null
    })
  })
  let allArr = newVal.concat(areas.value)
  const hash = {}
  const newAllArr = allArr.reduce((item,next) => {
    hash[next.id]? '' : hash[next.labelId] = true && item.push(next)
    return item
  }, [])
  contractLabelAll.value = newAllArr
  searchContractAll.value = newAllArr
  console.log('所有的标签', newAllArr)
},{
  deep: true
})
/**
 * 获取系统标签
 * */
const getLabels = () => {
  proxy.$api.getSystemLabels().then(res => {
    console.log('获取系统标签', res)
    areas.value = res.resultObject
    areas.value.map(item => {
      Object.assign(item, {
        id:  item.id.toString(),
        isSyc: true,
      })
    })
  })
}

const getIframe = () => {
  window.onmessage = (e) => {
    // console.log('接收到的消息', e)
    if (e.data.text) {
      formState.value.labelDetail = e.data.text
      console.log('接收到的消息', formState.value.labelDetail)
      // TextInfo.value.txt = e.data.text
      // selectText.value = e.data.text
    }
    if (e.data.top && e.data.cache) {
      formState.value.top = e.data.top
      formState.value.cache = e.data.cache
      if (contratInfo.value.scanPdf) {
        formState.value.labelDetail = '这是扫描版,无法选中文字哦'
      }
    }
    if (e.data.scanPdfX && e.data.scanPdfY) {
      formState.value.scanPdfX = e.data.scanPdfX
      formState.value.scanPdfY = e.data.scanPdfY
      formState.value.screenWidth = e.data.screenWidth
      formState.value.screenHeight = e.data.screenHeight
    }
  }
}
const showModal = () => {
  isSaveLabel.value = false
  selectTxt.value = undefined
  searchContractAll.value = contractLabelAll.value
  console.log('点击了没', searchTxt.value)
  if (!formState.value.labelDetail) {
    message.warn('请先在合同中选择内容，再选择标签')
  } else {
    visible.value = true
  }

}
const scanf = ref([])
const getPostion = () => {
  let postMsg =  {
    top: posionInfoChild.value.top,
    cache: posionInfoChild.value.cache,
    searchTxt: posionInfoChild.value.labelDetail
  }
  console.log('TextInfo.value.toString()', postMsg)
  let iframe = document.getElementById('parentIframe');
  iframe.contentWindow.postMessage(postMsg, '*')
  if (contratInfo.value.scanPdf && posionInfoChild.value.scanPdfX && posionInfoChild.value.scanPdfY) {
    if (posionInfoChild.value.screenWidth === window.screen.width) {
      console.log('这里撩妹')
      scanf.value.style.display = 'block'
      scanf.value.style.top = `${posionInfoChild.value.scanPdfY + 50}px`
      scanf.value.style.left = `${posionInfoChild.value.scanPdfX}px`
    }
    if (posionInfoChild.value.screenWidth > window.screen.width) {
      scanf.value.style.display = 'block'
      scanf.value.style.top = `${posionInfoChild.value.scanPdfY - 50}px`
      scanf.value.style.left = `${posionInfoChild.value.scanPdfX - 100}px`
    }
    if (posionInfoChild.value.screenWidth < window.screen.width) {
      scanf.value.style.display = 'block'
      scanf.value.style.top = `${posionInfoChild.value.scanPdfY + 200}px`
      scanf.value.style.left = `${posionInfoChild.value.scanPdfX}px`
    }
  }

}
/**
 * 保存标签
 * */
const handleOk = () => {
  if (formState.value.top && formState.value.cache !== 'undefined' && formState.value.cache) {
    console.log('这个值', formState)
    if (contractLabelAll.value.length > 0) {
      for (let item of contractLabelAll.value) {
        if (item.id === selectTxt.value) {
          formState.value.labelValue = item.labelValue
          formState.value.labelId = item.id
          console.log('执行这个了', formState.value)
          break
        } else {
          formState.value.labelValue = selectTxt.value
          console.log('执行这个了3444', formState.value)
        }
      }
    } else {
      formState.value.labelValue = selectTxt.value
      console.log('执行这个了3wwww444', formState.value)
    }
    Object.assign(formState.value, {
      conId: contratInfo.value.conId})
    console.log('传输过去了没', formState.value)
    proxy.$api.postContractLabel(formState.value).then(res => {
      if (res.resultCode === 0) {
        visible.value = false;
        message.success('保存标签成功')
        isSaveLabel.value = true
        formState.value.labelDetail = ''
        emit('saveLabel', isSaveLabel.value)
      }
    })
  } else {
    message.error('请重新滚动文档选中文本保存标签！')
  }
}
const closeLabelModel = () => {
  visible.value = false
  isSaveLabel.value = false
  formState.value.labelDetail = ''
}
const getMsg = () => {
  if (isIframe.value) {
    let iframe = document.getElementById('parentIframe');
    let url = `pdf/web/viewer.html?file=${contratInfo.value.url}?download=0&page=1&top=0&zoom=1.3`
    sessionStorage.setItem('pdfUrl', url)
    console.log('要穿的值', url)
    console.log('要穿的w值', props.originalContract)
    iframe.contentWindow.postMessage({url: url}, '*')
  }
}
const postSearchMsg = () => {
  let iframe = document.getElementById('parentIframe');
  iframe.contentWindow.postMessage({searchTxt: JSON.stringify(searchTxt.value)}, '*')
}
const handleSearch = (value) => {
  console.log('搜索的值', value)
  if (value) {
    // onSearchLabel(value)
    handleBlur(value)
    if (searchContractAll.value.length === 0) {
      handleChange(value)
    }
  }
}
const handleChange = (value) => {
  console.log('值', value)
  console.log('值2', selectTxt.value)
  selectTxt.value = value
}
const handleSelect = (value) => {
  console.log('选择的值', value)
  selectTxt.value = value
}
const handleBlur = (val) => {
  if (val) {
    // selectTxt.value = val
  }
  console.log('失去焦点选择的值',  selectTxt.value)
}
/**
 * 搜索标签
 * */
const filterOption = (input, option) => {
  console.log('input', input)
  console.log('option', option)
  if (option['labelValue'].indexOf(input) != -1) {
    return option
  } else {
    selectTxt.value = input
  }
}
/**
 * 下载
 * */
const dowMsg = ref(false)
const showDownModel = () => {
  downVisible.value = true
  dowMsg.value = false
}
const closeDownModel = () => {
  downVisible.value = false
  downForm.value.startPage = ''
  downForm.value.endPage = ''
  dowMsg.value = false
}
const downHandleOk = () => {
  Object.assign(downForm.value, {
    id: contratInfo.value.conId.toString(),
    contractName:  contratInfo.value.contractName
  })
  proxy.$api.getDownloadContractWithPageNum(downForm.value).then(res => {
    if (res.resultCode === 0) {
      dowMsg.value = true
      downVisible.value = false
      downForm.value.startPage = ''
      downForm.value.endPage = ''
    }
  })
}
const router = useRouter()
const goDown = () => {
  router.push({
    path: '/exportList'
  })
}
/**
 * 查看扫描件原件弹框
 * */
const showScan = () => {
  scanVisible.value = true
  setTimeout(() => {
    let iframeModel = document.getElementById('parentIframeModel');
    // 重新建立通信通道
    let url = `pdf/web/viewer.html?file=${contratInfo.value.newUrl}?download=0&page=1&top=0&zoom=1.3`
    console.log('要穿的值', url)
    iframeModel.contentWindow.postMessage({url: url}, '*');
  }, 1000)

}
onMounted(() => {
  // window.location.reload()
  getLabels()
  getIframe()
  // 路由刷新前
  window.addEventListener('beforeunload', () => {
    let iframe = document.getElementById('parentIframe');
    let url = `pdf/web/viewer.html?file=${contratInfo.value.url}?download=0&page=1&top=0&zoom=1.3`
    iframe.contentWindow.postMessage({url: url}, '*')
  });
  // 路由刷新后
  window.addEventListener('load', () => {
    let iframe = document.getElementById('parentIframe');
    // 重新建立通信通道
    let url = `pdf/web/viewer.html?file=${contratInfo.value.url}?download=0&page=1&top=0&zoom=1.3`
    console.log('要穿的值', url)
    iframe.contentWindow.postMessage({url: url}, '*');
  });
  $(document).ready(function() {
    $('iframe').on('load', function(){
      $(this).contents().find('body').css('overflow', 'hidden');
    });
  });
})

</script>

<style lang="scss" scoped>
#parentIframeModel {
  border: 0;
  body {
    overflow: hidden;
  }
}
#parentIframe {
  border: 0;
  body {
    overflow: hidden;
  }
}
.pdf-scan {
  color: #5e7ce0;
  font-size: 16px;
  position: absolute;
  left: 160px;
  top: 26px;
  cursor: pointer;
}
.pdf-model {
  margin-bottom: 24px;
  text-align: right;
  position: absolute;
  right: 45px;
  top: 23px;
  display: flex;
}
.from-btn-right {
  height: 62px;
  line-height: 62px;
  background: #ffffff;
  // box-shadow: 0px -4px 9px 0px rgba(0,0,0,0.09);
}
.pdf-form-item {
  display: flex;
  margin-bottom: 24px;
  span {
    width: 120px;
    line-height: 32px;
  }
}
.testIfram {
  position: relative;
}
.red-border {
  width: 200px;
  height: 50px;
  border: 1px solid red;
  position: absolute;
  display: none;
  //top: 542px;
  //left: 483px;
}
.downa {
  color: #5FB333;
  cursor: pointer;
}
</style>
